<script setup lang="ts">
import { computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'

const route = useRoute()
const router = useRouter()
const userStore = useUserStore()

const isLoggedIn = computed(() => userStore.isLoggedIn)
const isAdmin = computed(() => userStore.isAdmin)

const showNavbar = computed(() => route.name !== 'Login' && route.name !== 'Register')

const handleLogout = () => {
  userStore.logout()
  router.push('/login')
}

// 确保在组件挂载时状态正确
onMounted(() => {
  // 状态已经在 store 的 initFromStorage 中初始化了
})
</script>

<template>
  <div id="app">
    <!-- 导航栏 -->
    <nav class="navbar" v-if="showNavbar">
      <div class="nav-container">
        <router-link to="/" class="nav-logo">用户管理系统</router-link>
        <div class="nav-links">
          <router-link to="/" class="nav-link">首页</router-link>
          <router-link to="/profile" class="nav-link" v-if="isLoggedIn">个人信息</router-link>
          <router-link to="/admin/users" class="nav-link" v-if="isAdmin">用户管理</router-link>
          <router-link to="/dashboard" class="nav-link" v-if="isLoggedIn">仪表板</router-link>
          <router-link to="/login" class="nav-link" v-if="!isLoggedIn">登录</router-link>
          <router-link to="/register" class="nav-link" v-if="!isLoggedIn">注册</router-link>
          <button @click="handleLogout" class="nav-button" v-if="isLoggedIn">退出</button>
        </div>
      </div>
    </nav>

    <!-- 主要内容 -->
    <main class="main-content">
      <router-view />
    </main>
  </div>
</template>

<style>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  background-color: #f8fafc;
  color: #334155;
}

#app {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

/* 导航栏样式 */
.navbar {
  background: white;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  border-bottom: 1px solid #e2e8f0;
  position: sticky;
  top: 0;
  z-index: 100;
}

.nav-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 64px;
}

.nav-logo {
  font-size: 20px;
  font-weight: bold;
  color: #3b82f6;
  text-decoration: none;
}

.nav-links {
  display: flex;
  align-items: center;
  gap: 16px;
}

.nav-link {
  color: #64748b;
  text-decoration: none;
  padding: 8px 16px;
  border-radius: 6px;
  transition: all 0.2s;
  font-weight: 500;
}

.nav-link:hover {
  color: #3b82f6;
  background-color: #f1f5f9;
}

.nav-link.router-link-active {
  color: #3b82f6;
  background-color: #eff6ff;
}

.nav-button {
  background: #ef4444;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 6px;
  cursor: pointer;
  font-weight: 500;
  transition: background-color 0.2s;
}

.nav-button:hover {
  background: #dc2626;
}

/* 主要内容 */
.main-content {
  flex: 1;
  display: flex;
  flex-direction: column;
}
</style>